package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.UserMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.StringUtil;
import com.example.forum.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author: wenjingyuan
 * @Date: 2023/09/21/15:04
 * @Description:
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;
    @Override
    public void createNormalUse(User user) {
        //1.效验参数
        if(user==null || StringUtils.isEmpty(user.getUsername())
        || StringUtils.isEmpty(user.getNickname()) ||StringUtils.isEmpty(user.getPassword())
                || StringUtils.isEmpty(user.getSalt())
         ){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE .toString());
            //抛出异常，统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2.按照用户名查询信息
        User existUser=userMapper.selectByUserName(user.getUsername());
        if(existUser!=null){
            //打印日志
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }

        // 3. 新增用户流程,设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);
        // 当前日期
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        //写入数据库
         int row = userMapper.insertSelective(user);
         if(row!=1){
             //打印日志
             log.info(ResultCode.FAILED.toString());
             //抛出异常
             throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
         }
         //打印日志
        log.info("创建新用户成功，username="+user.getUsername()+".");
    }

    @Override
    public User selectByUserName(String username) {
        if(StringUtils.isEmpty(username)){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE .toString());
            //抛出异常，统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //返回查询的结果
        return userMapper.selectByUserName(username);
    }

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public User login(String username, String password) {
        //校验参数
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE .toString());
            //抛出异常，统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据用户名开始查询用户信息
        User user=userMapper.selectByUserName(username);
        //对查询的结果做非空校验
        if(user==null){
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN .toString()+"username"+username);
            //抛出异常，统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //做密码校验
        String encyPassword= MD5Util.md5salt(password,user.getSalt());
        if(!encyPassword.equalsIgnoreCase(user.getPassword())){
            //打印日志
            log.warn(ResultCode. FAILED_LOGIN.toString()+"密码错误,username"+username);
            //抛出异常，统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //打印登录成功日志
        log.info("登录成功,username:"+username);
        //登陆成功，返回用户信息
        return user;
    }

    @Override
    public User selectById(Long id) {
        //校验参数
        if(id == null){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE .toString());
            //抛出异常，统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //调用DAO的接口方法查询数据库
        User user = userMapper.selectByPrimaryKey(id);
        //返回结果
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        //校验参数
        if(id==null ||id<=0){
            //打印日志
            log.info(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }

        //参数没问题
        //调用DAO执行，返回user对象
        User user=userMapper.selectByPrimaryKey(id);
        if(user==null){
            //打印日志
            log.info(ResultCode.ERROR_IS_NULL.toString()+"user id="+id);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }

        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()+1);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            //打印日志
            log.warn(ResultCode.FAILED.toString());
            //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        //校验参数
        if(id==null ||id<=0){
            //打印日志
            log.info(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }

        //参数没问题
        //调用DAO执行，返回user对象
        User user=userMapper.selectByPrimaryKey(id);
        if(user==null){
            //打印日志
            log.info(ResultCode.ERROR_IS_NULL.toString()+"user id="+id);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }

        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()-1);
        if(updateUser.getArticleCount()<0){
            updateUser.setArticleCount(0);
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            //打印日志
            log.warn(ResultCode.FAILED.toString());
            //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        //参数校验
        if(user==null || user.getId()==0 || user.getId()<=0){
            //打印日志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //检验用户是否为空
        User existUser = userMapper.selectByPrimaryKey(user.getId());
        if(existUser==null){
            //用户不存在
            //打印日志
            log.info(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //定义一个标志位
        boolean chekAttr=false;//false代表校验不通过
        //重新new一个对象，防止传入的user修改其他的属性
        //当使用动态sql的时候，被赋值上没有经过检验的字段
        User updateUser=new User();
        //设置用户的id
        updateUser.setId(user.getId());
        //对每一个字段进行检验
        //先检查用户名
        if(!StringUtils.isEmpty(user.getUsername())
            && !user.getUsername().equals(existUser.getUsername())){
            //需要更新登录名
            User checkUser = userMapper.selectByUserName(user.getUsername());
            if(checkUser!=null){
                //用户已存在
                //打印日志
                log.info(ResultCode.FAILED_USER_EXISTS.toString());
                //抛出异常
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            //数据库中没有找到相应的，可以更新
            updateUser.setUsername(user.getUsername());
            //设置标志位
            chekAttr=true;
        }
        //再检查昵称
        if(!StringUtils.isEmpty(user.getNickname())
        && !user.getNickname().equals(existUser.getNickname())){
            //更新
            updateUser.setNickname(user.getNickname());
            //设置标志位
            chekAttr=true;
        }
        //设置性别
        if(user.getGender()!=null && user.getGender()!=existUser.getGender()){
            //更新
            updateUser.setGender(user.getGender());
            //合法性检验
            if(updateUser.getGender()>2 || updateUser.getGender()<0){
                updateUser.setGender((byte) 2);
            }
            //设置标志位
            chekAttr=true;
        }
        // 9. 校验邮箱
        if (!StringUtil.isEmpty(user.getEmail())
                && !user.getEmail().equals(existUser.getEmail())) {
            // 设置邮箱
            updateUser.setEmail(user.getEmail());
            // 更新标志位
            chekAttr = true;
        }
        // 9. 校验电话号码
        if (!StringUtil.isEmpty(user.getPhonenumber())
                && !user.getPhonenumber().equals(existUser.getPhonenumber())) {
            // 设置电话号码
            updateUser.setPhonenumber(user.getPhonenumber());
            // 更新标志位
            chekAttr = true;
        }
        // 10. 校验个人简介
        if (!StringUtil.isEmpty(user.getRemark())
                && !user.getRemark().equals(existUser.getRemark())) {
            // 设置电话号码
            updateUser.setRemark(user.getRemark());
            // 更新标志位
            chekAttr = true;
        }
        //根据标志位决定是否可以更新
        if(chekAttr==false){
            //打印日志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            //打印日志
            log.warn(ResultCode.FAILED.toString());
            //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        if(id==null ||id<=0 ||StringUtils.isEmpty(oldPassword)||StringUtils.isEmpty(newPassword)){
            //打印日志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询用户
        User user = userMapper.selectByPrimaryKey(id);
        //用户不存在
        if(user==null ||user.getDeleteState()==1){
            //打印日志
            log.info(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS)); 
        }
        //检验老密码是否正确
        //对老密码进行加密
        String oldEncryptPassword = MD5Util.md5salt(oldPassword,user.getSalt() );
        if(!oldEncryptPassword.equalsIgnoreCase(user.getPassword())){
            //打印日志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //生成一个新的盐
        String salt= UUIDUtil.UUID_32();
        //生成新密码的密文
        String encryptPassword=MD5Util.md5salt(newPassword,salt);
        //构造数据
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        updateUser.setPassword(encryptPassword);
        Date date=new Date();
        updateUser.setUpdateTime(date);
        //更新数据库的值
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            //打印日志
            log.warn(ResultCode.FAILED.toString());
            //抛出异常
            throw  new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
    }
}
